# This is a sample Python script.
import datetime
import hashlib
import json
import os
import time

import requests
from fastapi import FastAPI
from pydantic import BaseModel
from starlette.requests import Request
from starlette.responses import JSONResponse

import app_init
from tasks import task1
from app_init import init_token
from model import CommonResponse, CommonReport, Command
from my_logger import logger

app = FastAPI()

service_url = "https://devapi.beidiancloud.cn/machine-cloud"


# @app.post('/insert')
# def insert(people: People):
#     age_after_10_years = people.age + 10
#     msg = f'此人名字叫做：{people.name}，十年后此人年龄：{age_after_10_years}'
#     return {'success': True, 'msg': msg}


@app.post("/beidian-common-report")
async def common_report(cr: dict):
    # data= await request.json()

    if app_init.task_mode:

        task1.save_to_db_common_report.delay(cr)
    else:

        task1.save_to_db_common_report(cr)
    return JSONResponse(content={'code': 200, "data": ""})


@app.post("/beidian-response")
async def common_response(cr: dict):
    # print("命令回复：", cr)
    logger.info("命令回复：%s", json.dumps(cr))
    if cr["methodContent"] == "grid_param_datablock":
        task1.save_to_db_standard_read.delay(cr)
    callback_dict[cr["commandId"]] = cr
    return JSONResponse(content={'code': 200, "data": ""})


#
# @app.get("/beidian-response")
# async def common_response1(cr: CommonResponse):
#     print("命令回复：", cr)
#     logger.info("命令回复：" + cr)
#     callback_dict[cr.commandId] = cr
#     return JSONResponse(content={'code': 200, "data": ""})


@app.post("/command_switch")
async def command_switch(req: Command):
    data = {"productType": "KT.XXX.XBXXX",
            "devNo": req.devNo,
            "methodType": "air_conditioning_control",  # 即功能大类 0001 代表 07 标准明文读
            "methodContent": req.switch  # "switch_off",  # switch_on
            }
    return call(data)


@app.post("/command_read")
async def command_read(req: Command):
    data = {"productType": "KT.XXX.XBXXX",
            "devNo": req.devNo,
            "methodType": "pro07_standard_read",  # 即功能大类 0001 代表 07 标准明文读
            "methodContent": "grid_param_datablock"  # "switch_off",  # switch_on
            }
    return call(data)


@app.post("/command_params")
async def command_params(req: Command):
    # firmCode：品牌
    # switchOnOff:00=关;01=开
    # temperature:设定温度
    # airMode：空调控制器模式
    # （01 制热 02 制冷 04 送风 08 除湿）
    # windSpeed：00 自动，01 低档，02 中档，03 高档
    # windMode:扫风方式 00=关，01=上下 02=左右，03=上下+左右
    param = {
        "firmCode": "GL",
        "switchOnOff": "01",
        "temperature": "26",
        "airMode": "01",
        "windSpeed": "01",
        "windMode": "00"
    }
    getToken()
    global token
    data = {"productType": "KT.XXX.XBXXX",
            "devNo": req.devNo,
            "methodType": "air_controller",  # 即功能大类 0001 代表 07 标准明文读
            "methodContent": "infrared_set",  # 即功能小类，例如：a_voltage 代表 A 相电压
            "params": req.params,
            }

    return call(data)


@app.post("/command_response")
async def command_response(data: dict):
    if "commandId" in data and data["commandId"] in callback_dict:
        return JSONResponse(content=callback_dict[data["commandId"]])
    return JSONResponse(content={'code': 1000, "resultParams":{'msg': "命令已发送，暂收到响应" + data["commandId"]}})


@app.post("/refreshToken")
async def refreshToken():
    getToken()


def call(data: dict):
    if not token:
        getToken()
    logger.info(f"call {service_url}/api/device/command data={data} token= {token}")

    post = requests.post(f"{service_url}/api/device/command", json=data,
                         headers={"token": token})
    r = post.json()
    logger.info(f"call {service_url}/api/device/command result={r}")
    # if "commandId" in r and r["commandId"]:
    #     expire_time = datetime.datetime.now() + datetime.timedelta(minutes=1)
    #     while (expire_time - datetime.datetime.now()).seconds > 0:
    #         if r["commandId"] in callback_dict:
    #             return JSONResponse(content={'code': 200, "data": callback_dict[r["commandId"]]})
    #         time.sleep(1)
    return JSONResponse(content=r)


@app.get("/index")
async def index(request: Request):
    return JSONResponse(content={'name': {"demo": "hello world"}})


def print_hi(name):
    # Use a breakpoint in the code line below to debug your script.
    print(f'Hi, {name}')  # Press Ctrl+F8 to toggle the breakpoint.


def sha256_hash(string):
    hash_object = hashlib.sha256(string.encode('utf-8'))
    hex_dig = hash_object.hexdigest()
    return hex_dig


token = ""
callback_dict = dict()


def setCallback():
    if os.environ.get("airdata_profile", "") == "prod":
        data = {"callbackUrl": "http://47.116.193.24:6443/data_api/"}
    else:
        data = {"callbackUrl": "http://www.xiuwen.work:6008"}

    logger.info(f"设置回调{service_url}/api/account/callbackUrl/edit {data}")
    post = requests.post(f"{service_url}/api/account/callbackUrl/edit", json=data,
                         headers={"token": token})
    logger.info(f"设置结果{post.json()}")


def initToken():
    if init_token:
        getToken()

        setCallback()


def getToken():
    global token
    data = {"userName": "SHduolong", "time": str(int(datetime.datetime.now().timestamp())), "num": "1",
            "key": "138db80f42014296b7d6d57ead679a"}
    data["sign"] = sha256_hash(
        "userName=" + data["userName"] + "&time=" + data["time"] + "&num=" + data["num"] + "&key=" + data["key"])
    post = requests.post(f"{service_url}/api/sys/login", data=data)

    token = post.json()["token"]



# Press the green button in the gutter to run the script.
if __name__ == "__main__":
    import uvicorn

    print("airdata_profile=" + os.environ.get("airdata_profile", ""))
    if os.environ.get("airdata_profile", "") == "prod":

        initToken()
        logger.info(f"获取token={token}")
        logger.info("app started")

        #
        uvicorn.run(
            app='main:app',
            host="0.0.0.0",
            reload=False,
            port=6008,
        )
    else:
        import uvicorn

        getToken()
        logger.info("命令回复：%s", {'devNo': '240715027347'})
        # initToken()
        # data={'reportType': '0605', 'devNo': '240715027347',
        #  'deviceData': {'runningWord': '0c0280', 'monthPrepaidBalance': '0.00', 'monthSubsidyBalance': '0.00',
        #                 'prepaidBalance': '0.10', 'voltage': '226.6', 'frequency': '50.03', 'switchWord': '0010',
        #                 'reserveData': '000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
        #                 'current': '2.754', 'totalElectricEnergy': '217.23', 'todayOpenTime': '699',
        #                 'temperature': '24.3', 'subsidyBalance': '0.00', 'chargeBalance': '0.10',
        #                 'monthTotalPower': '148.30', 'reportTime': '2024-12-22 18:15:00', 'activePower': '0.6064'},
        #  'checkToken': 'U0hkdW9sb25nLDE3MzQ4NjI1MDIsN2M0YzJhMzg3YzhlMGI0MTk2M2M3NzhiYWQ4NWQxYTlhZmZiYzc2YTVjY2U1YThhMTMwMDY5ODdiMTBiYWFkOQ==',
        #  'deviceId': '34c48bee-62f2-4149-9479-7671cdeb1b5c', 'productType': 'KT.XXX.XBXXX',
        #  'reportTime': '2024-12-22 18:15:02'}
        # logger.info("app started")
        # logger.info("token="+token)
        # task1.save_to_db_common_report(data)
        uvicorn.run(
            app='main:app',
            host="0.0.0.0",
            reload=False,
            port=6008,
        )

# See PyCharm help at https://www.jetbrains.com/help/pycharm/
# 240715027438 3号楼骨二（304）
